package com.ruoyi.task.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysOperLog;
import com.ruoyi.system.service.ISysOperLogService;
import java.util.Arrays;
import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.task.domain.TaskDetail;
import com.ruoyi.task.mapper.TaskDetailMapper;
import com.ruoyi.task.service.ITaskDetailService;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 任务明细Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-12
 */
@Slf4j
@Service
public class TaskDetailServiceImpl implements ITaskDetailService
{
    @Autowired
    private TaskDetailMapper taskDetailMapper;


    @Autowired
    private ISysOperLogService sysOperLogService;

    /**
     * 查询任务明细
     * 
     * @param taskDetailId 任务明细主键
     * @return 任务明细
     */
    @Override
    public TaskDetail selectTaskDetailByTaskDetailId(Long taskDetailId)
    {
        TaskDetail taskDetail = taskDetailMapper.selectTaskDetailByTaskDetailId(taskDetailId);
        List<String> scenarionList = Arrays.asList(taskDetail.getScenariosType().split(",")) ;
        taskDetail.setScenariosTypeList(scenarionList);
        return taskDetail;
    }

    /**
     * 查询任务明细列表
     * 
     * @param taskDetail 任务明细
     * @return 任务明细
     */
    @Override
    public List<TaskDetail> selectTaskDetailList(TaskDetail taskDetail)
    {
        if (taskDetail.getScenariosType() != null) {
            taskDetail.setScenariosTypeList(
                    StringUtils.str2List(taskDetail.getScenariosType(), ",", true, true));
            taskDetail.setScenariosType(null);
        }
        return taskDetailMapper.selectTaskDetailList(taskDetail);
    }


    @Override
    public List<TaskDetail> queryCollectTaskDetail(TaskDetail taskDetail)
    {
        if (taskDetail.getScenariosType() != null) {
            taskDetail.setScenariosTypeList(
                    StringUtils.str2List(taskDetail.getScenariosType(), ",", true, true));
            taskDetail.setScenariosType(null);
        }
        return taskDetailMapper.queryCollectTaskDetail(taskDetail);
    }

    @Override
    public List<Map> queryReport(TaskDetail taskDetail) {
        if (taskDetail.getScenariosType() != null) {
            taskDetail.setScenariosTypeList(
                    StringUtils.str2List(taskDetail.getScenariosType(), ",", true, true));
            taskDetail.setScenariosType(null);
        }

        return taskDetailMapper.queryStatusReport(taskDetail);
    }

    /**
     * 新增任务明细
     * 
     * @param taskDetail 任务明细
     * @return 结果
     */
    @Override
    public int insertTaskDetail(TaskDetail taskDetail)
    {
        taskDetail.setCreateTime(DateUtils.getNowDate());
        return taskDetailMapper.insertTaskDetail(taskDetail);
    }

    /**
     * 修改任务明细
     * 
     * @param taskDetail 任务明细
     * @return 结果
     */
    @Override
    public int updateTaskDetail(TaskDetail taskDetail)
    {
        taskDetail.setUpdateTime(DateUtils.getNowDate());
        taskDetail.setMsg(StringUtils.left(taskDetail.getMsg(), 1000));
        return taskDetailMapper.updateTaskDetail(taskDetail);
    }

    @Override
    public int updateTaskDetailStatusByTaskId(TaskDetail taskDetail) {
        // 02-视频采集完成   03-视频采集失败
        if (StringUtils.equals("02", taskDetail.getTaskStatus())) {
            TaskDetail db = taskDetailMapper.queryTaskDetailByTaskId(taskDetail.getTaskId());
            if(db != null && StringUtils.equals("3", db.getTaskType())){
                long startTime = db.getCreateTime() != null ? db.getCreateTime().getTime() : 0;
                saveOperLog(taskDetail.getTaskId(), taskDetail.getMsg(), startTime);
            }
        }

        return taskDetailMapper.updateTaskDetailStatusByTaskId(taskDetail);
    }

    /**
     * 批量删除任务明细
     * 
     * @param taskDetailIds 需要删除的任务明细主键
     * @return 结果
     */
    @Override
    public int deleteTaskDetailByTaskDetailIds(Long[] taskDetailIds)
    {
        return taskDetailMapper.deleteTaskDetailByTaskDetailIds(taskDetailIds);
    }

    /**
     * 删除任务明细信息
     * 
     * @param taskDetailId 任务明细主键
     * @return 结果
     */
    @Override
    public int deleteTaskDetailByTaskDetailId(Long taskDetailId)
    {
        return taskDetailMapper.deleteTaskDetailByTaskDetailId(taskDetailId);
    }

    @Override
    public TaskDetail queryTaskDetailByTaskId(String taskId) {
        return taskDetailMapper.queryTaskDetailByTaskId(taskId);
    }

    /**
     * 保存日志
     * @param taskId
     * @param msg
     */
    private void saveOperLog(String taskId, String msg, long startTime){
        try {
            // "{\"taskId\":\"%s\",\"total\":%s,\"success\":%s,\"msg\":\"%s\"}"
            JSONObject json = JSONObject.parseObject(msg);
            int total = json.getIntValue("total", 0);
            int success = json.getIntValue("success", 0);

            SysOperLog operLog = new SysOperLog();
            operLog.setStatus(total == success ? BusinessStatus.SUCCESS.ordinal()
                    : BusinessStatus.FAIL.ordinal());
            // 请求的地址
            operLog.setOperIp("127.0.0.1");
            operLog.setOperUrl("/avapi/v0.2/wrap/mgt/bgtasks/capture");

            // 设置方法名称
            operLog.setMethod("com.ruoyi.task.service.impl.TaskDetailServiceImpl.updateTaskDetailStatusByTaskId()");
            // 设置请求方式
            operLog.setRequestMethod("POST");

            // 设置消耗时间
            long costTime = 0L;
            if (startTime > 0) {
                costTime = System.currentTimeMillis() - startTime;
            }
            operLog.setCostTime(costTime);

            operLog.setJsonResult(msg);
            operLog.setTitle("浩云分行采集任务");

            operLog.setOperatorType(1);
            operLog.setBusinessType(10);
            operLog.setOperLocation("内网IP");
            operLog.setOperName("system");

            // 保存数据库
            sysOperLogService.insertOperlog(operLog);
        } catch (Exception e) {
            log.error("taskDetail saveOperLog error :", e);
        }

    }
}
